#include "Server.h"
#include <iostream>

Server::~Server()
{
}

Server::Server(const char * ipAddr, int port) : pSocket()
{
        unsigned long address = inet_addr(ipAddr);
        if(address == INADDR_NONE)
                throw INADDR_NONE;
        _ipAddr.sin_family = AF_INET;
        _ipAddr.sin_port = htons(port);
        _ipAddr.sin_addr.S_un.S_addr = address;
}

void Server::StartListening()
{
	if(bind(_baseSocket, (sockaddr*)&_ipAddr, sizeof(sockaddr_in)) == SOCKET_ERROR)
		throw SOCKET_ERROR;
	if(listen(_baseSocket, 5) == SOCKET_ERROR)
		throw SOCKET_ERROR;
}

void Server::WaitForClient()
{
	sockaddr_in address;
	int len = sizeof(address);
	_clientSock = accept(_baseSocket, (sockaddr*)&address, &len);
	std::cout << "Client Connected: " << inet_ntoa(address.sin_addr) << " ,Port: " << ntohs(address.sin_port) << std::endl;
}

int Server::ReceiveBytes()
{
	return Receive(_recvBuffer, _clientSock, BUFFER_SIZE);
}